package com.astoolkit.workflow.task.net
{
	import com.astoolkit.workflow.BasePipelineTask;
	
	import mx.messaging.ChannelSet;
	import mx.rpc.AbstractOperation;
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	public class InvokeRemoteProcedure extends BasePipelineTask
	{
		public var remoteObject : RemoteObject;
		public var methodName : String;
		public var params : Array;
		public var ignoreResult : Boolean = true;
		public var result : *;
		public var destination : String;
		public var channelSet : ChannelSet;
		
		
		override public function prepare():void
		{
			super.prepare();
			result = null;
		}
		
		override public function begin(inRetain:Boolean=false):void
		{
			super.begin( inRetain );
			remoteObject = new RemoteObject();
			remoteObject.destination = destination;
			remoteObject.channelSet = channelSet;
			
			var op : AbstractOperation = remoteObject.getOperation( methodName );
			if( params && params.length > 0 )
			{
				var paramsObj : Object = {};
				for( var i : int = 0; i < params.length; i++ )
				{
					paramsObj[ "p"+i ] = params[i];
				}
			}
			var token : AsyncToken = op.send();
			if( ignoreResult )
			{
				complete();
			}
			else
			{
				token.addResponder( new Responder( onResult, onFault ) );
			}
		}
		
		private function onResult( inEvent : ResultEvent ) : void
		{
			result = inEvent.result;
			_pipelineData = result;
			complete();
		}

		private function onFault( inEvent : FaultEvent ) : void
		{
			fail( inEvent.fault.message, inEvent.fault );
		}
	
	}
}